package com.gjintel.workflow.trade.service.impl;

import com.gjintel.business.proj.model.ProjectBidInfo;
import com.gjintel.business.proj.model.ProjectInfo;
import com.gjintel.business.proj.service.INewNotifyService;
import com.gjintel.business.proj.service.IProjectBidService;
import com.gjintel.business.proj.service.IProjectInfoService;
import com.gjintel.business.proj.service.impl.NewNotifyServiceImpl;
import com.gjintel.business.webcontent.model.WebContent;
import com.gjintel.framework.cache.InitCacheData;
import com.gjintel.framework.cache.InitCacheData.CacheType;
import com.gjintel.framework.common.service.IDepositService;
import com.gjintel.framework.constant.ActivitiMap;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.constant.ProjectStatus;
import com.gjintel.framework.dataset.model.DataSet;
import com.gjintel.framework.dataset.service.impl.DataSetServiceImpl;
import com.gjintel.framework.dict.model.Dictionary;
import com.gjintel.framework.holidayset.service.IHolidaySetService;
import com.gjintel.framework.log.model.LogInfo;
import com.gjintel.framework.log.model.TSysWarningLog;
import com.gjintel.framework.log.service.impl.MessageServiceImpl;
import com.gjintel.framework.log.util.LogUtil;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.role.service.IRoleService;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.DictUtil;
import com.gjintel.framework.util.FileResUtil;
import com.gjintel.sdk.util.DateUtils;
import com.gjintel.sdk.util.StringUtil;
import com.gjintel.sdk.util.WordHandler;
import com.gjintel.workflow.trade.service.INBExecutionService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 不评标流程
 * @author wei
 *
 */
@Service("nBExecutionService")
public class NBExecutionServiceImpl implements INBExecutionService {

	@Autowired
	private IProjectInfoService projectInfoService;

	@Autowired
	private WorkflowProcessInstanceServiceImpl workflowProcessInstanceService;
	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private IHolidaySetService holidaySetServiceImpl;
	
	@Autowired
	private DataSetServiceImpl dataSetService;
	
	@Autowired
	private INewNotifyService newNotifyService;
	
	@Autowired
	private IRoleService roleService;

	@Autowired
	private IProjectBidService projectBidService;
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
	private SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	
	final String modelPath = IDepositService.class.getResource("/publicity").getPath();
	/**
	 * 竞价公示暂停申请
	 */
	private Integer SHOT_PAUSE_APPLY=299;
	
	/**
	 * 中标公示暂停
	 */
	private Integer WINBID_PAUSE_APPLY=300;

	@Autowired
	private IHolidaySetService holidaySetService;
	
	@Autowired
	private MessageServiceImpl messageService;

	@Override
	@Transactional(readOnly = false)
	public void editNoticeAndStatus(Execution execution, Integer status) {
		//发送通知，修项目改状态
		String processId = execution.getProcessInstanceId();
		ProjectInfo pi = projectInfoService.getProjectByProcessId(processId);
		Task task = workflowProcessInstanceService.findTask(processId);
		String info="无";
		if(task!=null){
			info = task.getName();
		}
		// 根据 所处的任务来判断需要 进行消息提醒
		addMessageHandle(pi,status,info);
		
		if(!SHOT_PAUSE_APPLY.equals(status)//竞价、中标公示暂停申请不修改项目状态
				&&!WINBID_PAUSE_APPLY.equals(status)){
			pi.setStatus(status);//修改成下一个项目状态
		}
		
		//数据处理
		handData(status,pi);
		
		System.err.println("NBExecutionServiceImpl.editNoticeAndStatus()------------------>["+info+"] 任务结束： 状态："+status);
		
		this.projectInfoService.saveOrUpdate(pi);
	}

	/**
	 * 根据项目状态和任务名来发送消息
	 * @param pi
	 * @param status
	 */
	private void addMessageHandle(ProjectInfo pi, Integer status,String taskInfo) {
		List<User> financelist = roleService.findUserByRoleId(ActivitiMap.FINANCE_ID);
		List<User> users =new ArrayList<>();
		User user=null;
		switch (status) {
		case 2:
			System.err.println("编制审核 提醒");
			//分配的中心审核人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getAuditId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.AUDIT_PRO, users, pi);
			break;
		case 3:
			System.err.println("待分配 提醒");
			//获取所有的分配人
			users.clear();
			users = roleService.findUserByRoleId(ActivitiMap.SYSTEM_ID);
			newNotifyService.putNotify(NewNotifyServiceImpl.AUDIT_PRO, users, pi);
			break;
		case 6:
			System.err.println("编制审核超时未确认 提醒");
			//采购人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getCreateId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.COMPILEOVERTIME, users, pi);
			break;
		case 7:
			if(!"中心审核员处理".equals(taskInfo)){
				System.err.println("竞价公告发布 提醒");
				//采购人
				users.clear();
				user = this.projectInfoService.get(User.class, pi.getCreateId());
				users.add(user);
				newNotifyService.putNotify(NewNotifyServiceImpl.OPEN_BID, users, pi);
				
				//中心审核人
				users.clear();
				user = this.projectInfoService.get(User.class, pi.getAuditId());
				users.add(user);
				newNotifyService.putNotify(NewNotifyServiceImpl.OPEN_BID, users, pi);
			}else{//重启项目
				System.err.println("竞价重启 提醒");
				//采购人
				users.clear();
				user = this.projectInfoService.get(User.class, pi.getCreateId());
				users.add(user);
				newNotifyService.putNotify(NewNotifyServiceImpl.RESTART, users, pi);
			}
			
			break;
		case 25:
			System.err.println("编制审核不通过 提醒");
			//采购人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getCreateId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.ESTABLISH, users, pi);
			break;
		case 932:
			System.err.println("中标待选择 提醒");
			//采购人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getCreateId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.BID_WAY, users, pi);
			break;
		case 91:
			if (!"采购人确定中标方式".equals(taskInfo)) {
				System.err.println("中标中心确认 提醒");
				//中心审核人
				users.clear();
				user = this.projectInfoService.get(User.class, pi.getAuditId());
				users.add(user);
				newNotifyService.putNotify(NewNotifyServiceImpl.CENTER_CONFIRM, users, pi);
			}
			break;
		case 92:
			System.err.println("流标中心确认 提醒");
			//中心审核人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getAuditId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.CENTER_CONFIRM, users, pi);
			break;
		case 299:
			System.err.println("竞价暂停申请 提醒");
			//中心审核人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getAuditId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.SUSPEND, users, pi);
			break;
		case 300:
			System.err.println("中标暂停申请 提醒");
			//采购人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getCreateId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.BID_PAUSE, users, pi);
			break;
		case 10:
			if("中心处理质疑".equals(taskInfo)){
				System.err.println("中标重启 提醒");
				//采购人
				users.clear();
				user = this.projectInfoService.get(User.class, pi.getCreateId());
				users.add(user);
				newNotifyService.putNotify(NewNotifyServiceImpl.RESTART, users, pi);
			}
			break;
		case 11:
			System.err.println("发放中标通知书 提醒");
			//中心审核人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getAuditId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.BID_ADVICE_NOTE, users, pi);
			break;
		case 12:
			System.err.println("上传合同  提醒");
			//采购人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getCreateId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.UPLOAD_CONTRACT, users, pi);
			
			//财务管理员
			for(User finance : financelist){
				TSysWarningLog financeLog = new TSysWarningLog();
				financeLog.setTitle("退还非中标保证金");
				financeLog.setContents("您好," + pi.getName() + "项目的非中标保证金可以开始退还。");
				financeLog.setProjectId(pi.getId());
				financeLog.setWarnType("8"); //	BID_NOTICE_END="8"//中标公示结束
				financeLog.setReaderId(finance.getId());
				financeLog.setReaderName(finance.getName());
				financeLog.setWarringId("");
				messageService.saveOrUpdate(financeLog);
			  }  
			break;
		case 88:
			System.err.println("上传合同  提醒");
			//采购人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getCreateId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.CONTRACT_DEBLOCKING, users, pi);
			//中心审核人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getAuditId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.CONTRACT_DEBLOCKING, users, pi);
			break;
		case 27:
			System.err.println("合同审核 提醒");
			//中心审核人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getAuditId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.CONTRACT_AUDIT, users, pi);
			break;
		case 28:
			System.err.println("上传合同  提醒");
			//采购人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getCreateId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.CONTRACT_AUDIT_UNPASS, users, pi);
			break;
		case 14:
			System.err.println("上传验收报告  提醒");
			//采购人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getCreateId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.UPLOAD_REPORT, users, pi);
			break;
		case 140:
			System.err.println("验收待审核 提醒");
			//中心审核人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getAuditId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.REPORT_AUDIT, users, pi);
			break;
		case 142:
			System.err.println("重新上传验收报告  提醒");
			//采购人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getCreateId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.UPDATE_REPORT, users, pi);
			break;
		case 141:
			System.err.println("结项确认  提醒");
			//中心审核人
			users.clear();
			user = this.projectInfoService.get(User.class, pi.getAuditId());
			users.add(user);
			newNotifyService.putNotify(NewNotifyServiceImpl.PROJECT_END, users, pi);		
			//财务管理员			
			for(User finance : financelist){
				TSysWarningLog financeLog = new TSysWarningLog();
				financeLog.setTitle("履约保证金");
				financeLog.setContents("您好," + pi.getName() + "项目的履约保证金可以开始退还。");
				financeLog.setProjectId(pi.getId());
				financeLog.setWarnType("8"); //	BID_NOTICE_END="8"//中标公示结束
				financeLog.setReaderId(finance.getId());
				financeLog.setReaderName(finance.getName());
				financeLog.setWarringId("");
				messageService.saveOrUpdate(financeLog);
			  }  
			break;
		case 24:
			System.err.println("项目撤销  提醒");
			//财务管理员
			for(User finance : financelist){
				TSysWarningLog financeLog = new TSysWarningLog();
				financeLog.setTitle("保证金");
				financeLog.setContents("您好," + pi.getName() + "项目的保证金可以开始退还。");
				financeLog.setProjectId(pi.getId());
				financeLog.setWarnType("8"); //	BID_NOTICE_END="8"//中标公示结束
				financeLog.setReaderId(finance.getId());
				financeLog.setReaderName(finance.getName());
				financeLog.setWarringId("");
				messageService.saveOrUpdate(financeLog);
			  }  			
		default:
			break;
		}
	}

	/**
	 * 数据处理
	 * @param status
	 * @param pi
	 */
	private void handData(Integer status,ProjectInfo pi) {
		//流标公示结束
		if (status.equals(ProjectStatus.FLOW_DOWN.toString())) {// 流标公示结束，设置结束时间
			pi.setEndTime(new Date());
			// 项目跨度
			int allDays = DateUtils.daysBetween(pi.getCreateTime(), pi.getEndTime());
			pi.setAllDays(allDays);
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void isFlowBidTaskService(Execution execution) {
		String processId="";
		if(execution!=null){
			processId=execution.getProcessInstanceId();
		}
		ProjectInfo pi = projectInfoService.getProjectByProcessId(processId);
		Map<String, Object> variables = new HashMap<>();
		Integer flowBid;
		Integer flowOrHitShow;
		
		//设定不是重新编辑,后面条件流程判断用
		variables.put("reEdit", false);
		
		//判断是否流标 flowBid
		if (projectInfoService.getProjectBidderByProjId(pi.getId(), true) < 3) {// 投标单位少于3家，流标待确认
			flowBid=Integer.valueOf(ProjectStatus.WAIT_FAIL_SURE.toString());
			flowOrHitShow=Integer.valueOf(ProjectStatus.SHOWING_FLOW.toString());
			pi.setCancelReason(Constant.FLOW_CONTENT);//设置流标内容，投标单位不足三家
			pi.setChooseType(Constant.CHOOSE_TYPE_SYSTEM_LESS3_Flow);//不足三家流标（系统默认选择中标结果）
			this.projectInfoService.saveOrUpdate(pi);
			//重新设置流程v1.2：
			variables.put("noEnoughBidderFlow", true);
			
		}else{//中标待选择
			flowBid=Integer.valueOf(ProjectStatus.WAIT_WIN_CHOICE.toString());
			flowOrHitShow=Integer.valueOf(ProjectStatus.SHOWING.toString());
			//中标待选择超时时间(三个工作日)
			//从数据字典中获取中标待选择超时周期（不资质后审）
			Dictionary choiceTimeCycleDir = DictUtil.dict("busi_set", "choiceTimeCycle" + "");
			Integer cycle=3;
			if(choiceTimeCycleDir!=null){
				cycle=Integer.valueOf(choiceTimeCycleDir.getRemark());
				System.err.println("NBExecutionServiceImpl.isFlowBidTaskService()------------------>不资质后审中标待选择超时周期:["+cycle+"]天，执行了");
			}
			String choiceDate = DateUtils.computeWorkDayDateStr(holidaySetServiceImpl, new Date(),cycle);// (工作日)公示时间
			variables.put("choiceTime", StringUtil.getISODate(choiceDate));//中标待选择超时时间
			
			//从数据字典中获取中标待选择超时周期（资质后审）
			Dictionary afterChoiceTimeCycleDir = DictUtil.dict("busi_set", "afterChoiceTimeCycle" + "");
			if(afterChoiceTimeCycleDir!=null){
				cycle=Integer.valueOf(afterChoiceTimeCycleDir.getRemark());
				System.err.println("NBExecutionServiceImpl.isFlowBidTaskService()------------------>资质后审中标待选择超时周期:["+cycle+"]天，执行了");
			}
			String afterChoiceDate = DateUtils.computeWorkDayDateStr(holidaySetServiceImpl, new Date(), cycle);// (工作日)公示时间
			variables.put("afterChoiceTime", StringUtil.getISODate(afterChoiceDate));//中标待选择超时时间
			
			//重新设置流程v1.2：
			variables.put("noEnoughBidderFlow", false);
		}
		variables.put("flowBid", flowBid);// 流标/中标待确认
		variables.put("flowOrHitShow", flowOrHitShow);// 流标/中标公式中
		
		runtimeService.setVariables(execution.getId(), variables);
		LogUtil.addLog(new LogInfo("["+pi.getName()+"]"+"flowBid:["+flowBid+"]执行了", "1", "系统", String.valueOf(LogUtil.LogType.ADD.ordinal()), this.getClass().getSimpleName(), "1"));
		System.err.println("NBExecutionServiceImpl.isFlowBidTaskService()------------------>判断是否流标 flowBid:["+flowBid+"]执行了");
	}

	@Override
	@Transactional(readOnly = false)
	public void publishHitPublicity(Execution execution,Boolean isOverTime) {
		String processId="";
		if(execution!=null){
			processId=execution.getProcessInstanceId();
		}
		ProjectInfo pi = projectInfoService.getProjectByProcessId(processId);
		if (isOverTime) {//超时未选择中标单位，系统以最低价中标
			//将所有投标信息赋值为不是中标单位
			ProjectBidInfo pbInfo=new ProjectBidInfo();
			pbInfo.setProjectId(pi.getId());
			List<ProjectBidInfo> bidList = this.projectInfoService.findProjectBidListByProjectId(null, pbInfo);
			for (ProjectBidInfo pb : bidList) {
				if(pb.getIsMultHit()){
					pb.setIsMultHit(false);//为中标单位
					this.projectInfoService.saveOrUpdate(pb);
				}
			}
			
			//获取最低价中标单位id
			ProjectBidInfo hitBidInfo=this.projectInfoService.getTendeeByProjId(pi.getId());
			hitBidInfo.setIsMultHit(true);//为中标单位
			this.projectInfoService.saveOrUpdate(hitBidInfo);
		}
		
		//生成中标公示新闻
		WebContent web = generateHitPublicity(pi,null,false);
		this.projectInfoService.saveOrUpdate(web);
		runtimeService.setVariable(execution.getId(), "documentId", web.getId());//将中标公示新闻信息id存入流程中
		LogUtil.addLog(new LogInfo("["+pi.getName()+"]"+"[生成中标公示] 执行了", "1", "系统", String.valueOf(LogUtil.LogType.ADD.ordinal()), this.getClass().getSimpleName(), "1"));
		System.err.println("NBExecutionServiceImpl.buyerChoiceBidderTaskService()------------------>[生成中标公示] 执行了");
	}

	@Override
	@Transactional(readOnly = false)
	public void publishFlowPublicity(Execution execution, Boolean isDisplay) {
		String processId="257512";
		if(execution!=null){
			processId=execution.getProcessInstanceId();
		}
		ProjectInfo pi = projectInfoService.getProjectByProcessId(processId);
		//生成流标公示新闻
		WebContent web = generateFlowPublicity(pi,null,isDisplay);
		this.projectInfoService.saveOrUpdate(web);
		runtimeService.setVariable(execution.getId(), "documentId", web.getId());//将中标公示新闻信息id存入流程中
		LogUtil.addLog(new LogInfo("["+pi.getName()+"]"+"[生成/生成发布流标公示] 执行了", "1", "系统", String.valueOf(LogUtil.LogType.ADD.ordinal()), this.getClass().getSimpleName(), "1"));
		System.err.println("NBExecutionServiceImpl.buyerChoiceBidderTaskService()------------------>[生成/生成发布流标公示] 执行了");
	}

	@Override
	@Transactional(readOnly = false)
	public void displayPublicity(Execution execution) {
		String processId="257512";
		if(execution!=null){
			processId=execution.getProcessInstanceId();
		}
		ProjectInfo pi = projectInfoService.getProjectByProcessId(processId);
		
		Integer flowOrHitShow=(Integer) runtimeService.getVariable(execution.getId(), "flowOrHitShow");
		String webId = (String) runtimeService.getVariable(execution.getId(), "documentId");    //获得发文的id
		WebContent web = this.projectInfoService.get(WebContent.class, webId);
		
		if(Integer.valueOf(ProjectStatus.SHOWING.toString()).equals(flowOrHitShow)){//中标公示
			generateHitPublicity(pi, web,true);//重新生成中标公示
		}else{//流标公示
			generateFlowPublicity(pi,web, true);
		}

		this.projectInfoService.saveOrUpdate(web);
		LogUtil.addLog(new LogInfo("["+pi.getName()+"]"+"[显示公示] 执行了", "1", "系统", String.valueOf(LogUtil.LogType.ADD.ordinal()), this.getClass().getSimpleName(), "1"));
		System.err.println("NBExecutionServiceImpl.buyerChoiceBidderTaskService()------------------>[显示公示] 执行了");
	}

	@Override
	public void displayPublicityNew(Execution execution) {
		String processId="257512";
		if(execution!=null){
			processId=execution.getProcessInstanceId();
		}
		ProjectInfo pi = projectInfoService.getProjectByProcessId(processId);

		Integer flowOrHitShow=(Integer) runtimeService.getVariable(execution.getId(), "flowOrHitShow");
		String webId = (String) runtimeService.getVariable(execution.getId(), "documentId");    //获得发文的id
		WebContent web = this.projectInfoService.get(WebContent.class, webId);

		generateFlowPublicity(pi,web, true);

		this.projectInfoService.saveOrUpdate(web);
		LogUtil.addLog(new LogInfo("["+pi.getName()+"]"+"[显示公示] 执行了", "1", "系统", String.valueOf(LogUtil.LogType.ADD.ordinal()), this.getClass().getSimpleName(), "1"));
		System.err.println("NBExecutionServiceImpl.displayPublicityNew()------------------>[显示公示] 执行了");
	}

    @Override
    public void setBuyerConfirmOvertime(Execution execution) {
        String processId="";
        if(execution!=null){
            processId=execution.getProcessInstanceId();
        }
        //获取项目信息
        ProjectInfo pi= projectInfoService.getProjectByProcessId(processId);
		ProjectBidInfo pbInfo=new ProjectBidInfo();
		pbInfo.setProjectId(pi.getId());
		//取出项目投标信息
		List<ProjectBidInfo> bidList = this.projectInfoService.findProjectBidListByProjectId(null, pbInfo);
		//把原来中标单位设为不中标
		for (ProjectBidInfo pb : bidList) {
			if(pb.getIsMultHit()){
				pb.setIsMultHit(false);//为中标单位
				this.projectBidService.saveOrUpdate(pb);
			}
		}
		//获取最低价中标单位
		ProjectBidInfo hitBidInfo=this.projectInfoService.getTendeeByProjId(pi.getId());
		if(hitBidInfo!=null){
			hitBidInfo.setIsMultHit(true);//为中标单位
			this.projectBidService.saveOrUpdate(hitBidInfo);
		}
        pi.setChooseType(Constant.CHOOSE_TYPE_SYSTEM_CHOOSE_MIN);
        projectInfoService.saveOrUpdate(pi);
    }

    /**
	 * 生成中标公示
	 * @param pi
	 * @param isDisplay
	 * @return
	 */
	@SuppressWarnings("all")
	private WebContent generateHitPublicity(ProjectInfo pi,WebContent web, boolean isDisplay) {
		String tempContent=CommUtil.readStringFromFile(modelPath+"/"+"hitPublicity.html","utf-8");//模板文件目录
		Map map = new HashMap();
		map.put("project", pi);
		map.put("hitTime", sdf.format(new Date()));// 发布时间
		map.put("bidStartTime", sdf.format(pi.getBidStartTime()));// 发布时间(开标时间)

		if(isDisplay){//显示

			//如果中标时间为空，则保存
			if(pi.getHitShowStartTime()==null){
				pi.setHitShowStartTime(new Date());
				DataSet dataset = (DataSet)this.dataSetService.get(DataSet.class, Constant.DATASET_ID);
				String publicityDate = DateUtils.computeWorkDayDateStr(this.holidaySetService, new java.util.Date(), dataset.getBuyerPublicity().intValue());
				pi.setHitShowStartTime(new java.util.Date());
				try {
					pi.setShowEndTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(publicityDate));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				projectInfoService.saveOrUpdate(pi);
			}

			map.put("hitShowStartTime", sdf.format(pi.getHitShowStartTime()));// 中标公示期开始时间
			map.put("showEndTime", sdf.format(pi.getShowEndTime()));// 中标公示期结束时间
		}else{
			map.put("hitShowStartTime", null);// 中标公示期开始时间
			map.put("showEndTime", null);// 中标公示期结束时间
		}
		
		//公示附件
		String pubResName = "";
		List<Resources> resList = FileResUtil.findResources(pi.getId());
		for (Resources resource : resList) {
			if (resource.getFunctionFlog() == 27) {// 公示附件
				pubResName += "<a href='../web/fileView?resId=" + resource.getId() + "'>" + resource.getOldName()
						+ "</a> ";
			}
		}
		map.put("pubResName", pubResName);
		
		// 竞价内容附件，投标人提交的附件
		//getShotContentRes(pi, map);
		
		// 中标单位信息
		List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(pi.getId());
		map.put("bidInfos", bidInfos);

		//获取所有投标信息
		ProjectBidInfo pro = new ProjectBidInfo();
		pro.setProjectId(pi.getId());
		List<ProjectBidInfo> bidInfoList = this.projectInfoService.findProjectBidListByProjectId(null, pro);
		map.put("allBidInfos",bidInfoList);
		
		//生成内容
		String content = CommUtil.freemarkerProcess(map,tempContent);
		
		// 插入新闻数据
		if(web==null){
			web=new WebContent();
		}
		web.setTitle("【"+pi.getCatagoryName()+"】"+ pi.getName() + "中标公告");
		web.setContent(content);
		web.setCreaterId(ActivitiMap.SUPERADMIN_ID);
		web.setCreateTime(new Date());
		web.setCreaterName("系统");
		web.setProjectId(pi.getId());
		web.setType("32");
		web.setDeptId("1");
		if(isDisplay){
			web.setIsDisplay(0);// 显示
			web.setEndShowTime(pi.getShowEndTime());// 设置展示结束时间
		}else{
			web.setIsDisplay(1);// 不显示
		}
		
		return web;
	}
	
	/**
	 * 生成流标公示
	 * @param pi
	 * @return
	 */
	@SuppressWarnings("all")
	private WebContent generateFlowPublicity(ProjectInfo pi,WebContent web,Boolean isDisplay){
		String tempContent=CommUtil.readStringFromFile(modelPath+"/"+"flowPublicity.html","utf-8");//模板文件目录
		Map map = new HashMap();
		map.put("flowReason", pi.getCancelReason());
		map.put("project", pi);
		map.put("flowTime", sdf.format(new Date()));
		//公示附件
		String pubResName = "";
		List<Resources> resList = FileResUtil.findResources(pi.getId());
		for (Resources resource : resList) {
			if (resource.getFunctionFlog() == 27) {// 公示附件
				pubResName += "<a href='../web/fileView?resId=" + resource.getId() + "'>" + resource.getOldName()
						+ "</a> ";
			}
		}
		map.put("pubResName", pubResName);
		
		//生成内容
		String content = CommUtil.freemarkerProcess(map,tempContent);
		
		// 插入新闻数据
		if(web==null){
			web=new WebContent();
		}
		web.setTitle("【"+pi.getCatagoryName()+"】" + pi.getName() + "流标公告");
		web.setContent(content);
		web.setCreaterId(ActivitiMap.SUPERADMIN_ID);
		web.setCreateTime(new Date());
		web.setCreaterName("系统");
		web.setDeptId("1");
		web.setProjectId(pi.getId());
		web.setType("33");
		if (isDisplay) {
			web.setIsDisplay(0);//显示
			
			// 流标公示结束时间
			Date flowShowEndTime=getFlowShowEndTime();
			web.setEndShowTime(pi.getFlowShowEndTime());// 设置展示结束时间
		}else{
			web.setIsDisplay(1);//不显示
		}
		return web;
	}

	/**
	 * 获取流标公示结束时间
	 * @return
	 */
	private Date getFlowShowEndTime() {
		Date flowShowEndTime=new Date();
		// 流标公示期变量
		DataSet dataset = dataSetService.get(DataSet.class, Constant.DATASET_ID);
		int publicity = dataset.getFlowPublicity();// 公示天数
		String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetServiceImpl, new Date(), publicity);// (工作日)公示时间
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			flowShowEndTime=format.parse(publicityDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return flowShowEndTime;
	}

	@Override
	@Transactional(readOnly = false)
	public void publishShotPublicity(Execution execution) {
		String processId="257512";
		if(execution!=null){
			processId=execution.getProcessInstanceId();
		}
		ProjectInfo pi = projectInfoService.getProjectByProcessId(processId);
		
		pi.setCompetReleaseTime(new Date());//竞价公告发布时间
		projectInfoService.saveOrUpdate(pi);
		
		// 发布竞标公告
		WebContent web = generateShotPublicity(pi);
		projectInfoService.saveOrUpdate(web);
	}
	
	

	/**
	 * 生成竞价公告
	 * @param pi
	 * @return
	 */
	@SuppressWarnings("all")
	private WebContent generateShotPublicity(ProjectInfo pi) {
		//重新生成竞价文件(缺少项目编号)
		generateShotWord(null, pi);
		
		
		String tempContent=CommUtil.readStringFromFile(modelPath+"/"+"shotPublicity.html","utf-8");//模板文件目录
		Map map = new HashMap();
		map.put("project", pi);
		
		// 附件
		String resName = "";
		List<Resources> resList = FileResUtil.findResources(pi.getId());
		for (Resources resource : resList) {
			if (resource.getFunctionFlog() == 5) {// 竞价文件
				resName += "<a href='../web/fileView?resId=" + resource.getId() + "'>" + resource.getOldName()
						+ "</a>  <br/>";
			}
			if (resource.getFunctionFlog() == 8) {// 采购需求
				resName += "<br><a href='../web/fileView?resId=" + resource.getId() + "'>" + resource.getOldName()
						+ "</a>  <br/>";
			}
		}
		map.put("resName", resName);
		
		//生成内容
		String content = CommUtil.freemarkerProcess(map,tempContent);

		// 插入新闻数据
		WebContent web = new WebContent();
		// 标题
		String title ="【"+pi.getCatagoryName()+"】"+  pi.getName() + "（" + pi.getCode() + "）开标时间："
				+ sdfTime.format(pi.getBidStartTime());
		web.setTitle(title);
		web.setContent(content);
		web.setCreaterId(ActivitiMap.SUPERADMIN_ID);
		web.setCreateTime(new Date());
		web.setCreaterName("系统");
		web.setDeptId("1");
		web.setProjectId(pi.getId());
		web.setType("31");
		web.setEndShowTime(pi.getBidStartTime());// 设置展示结束时间
		web.setIsDisplay(0);//显示
		return web;
	}

	
	/**
	 * @description 生成竞价文件
	 * @author wwang
	 * @date 2016-8-29
	 * @param request
	 * @param projectId
	 * @param project
	 */
	@SuppressWarnings("all")
	private void generateShotWord(HttpServletRequest request, ProjectInfo project) {
		// 数据处理
		project.setFundFromName(DictUtil.dict("fundFroms", project.getFundFrom()).getName());// 资金来源

		String oldName = project.getName() + "-竞价文件.doc";

		// 判断使用world模板版本
		String worldXmlPath = "nb-trade-goods.xml";// 模板名称
		// 项目类型
		if (Constant.PROJECTCATAGORY_GOODSID.equals(project.getCatagoryId())) {// 货物类
			worldXmlPath = "nb-trade-goods.xml";
		} else if (Constant.PROJECTCATAGORY_SERVICEID.equals(project.getCatagoryId())) {// 服务类
			worldXmlPath = "nb-trade-service.xml";
		} else if (Constant.PROJECTCATAGORY_ENGINEERINGID.equals(project.getCatagoryId())) {// 工程类
			worldXmlPath = "nb-trade-engineering.xml";
		} else if (Constant.PROJECTCATAGORY_PROPERTYID.equals(project.getCatagoryId())) {// 产权类
			// TODO 产权类的竞价文件模板
			worldXmlPath = "nb-trade-goods.xml";
		}

		// 得到文件的相对路径
		String relativePath = File.separator + "project";
		String rootPath=(String) InitCacheData.getInstance().getCacheDataMap(CacheType.SERVER_ROOT_PATH);
		String uploadPath = rootPath+"file_resource"+ relativePath;
		
		File filePath = new File(uploadPath);
		// 判断文件夹是否存在，如果不存在给与创建出来
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		// 保存文档到res数据
		List<Resources> resList = FileResUtil.findResources(project.getId());
		// 删除之前的生成的竞价文件
		for (Resources resources : resList) {
			if (resources.getFunctionFlog() == 5) {
				FileResUtil.deleteFile(resources.getId(), rootPath);
			}
		}
		Resources res = new Resources();
		String exeName = ".doc";
		res.setExeName(exeName);
		res.setFilePath(relativePath);
		res.setFileSize(50L);
		res.setOldName(oldName);
		res.setBusinessId(project.getId());
		res.setFunctionFlog(5);// 设置文件功能类型(竞价文件)
		FileResUtil.addFileRes(res); // 保存文件记录

		// 生成文档
		// world保存的真实路径
		String path = uploadPath + "/" + res.getId() + ".doc";
		Map map = new HashMap();
		// 时间
		map.put("maxDate", DateUtils.dataToUpper(new Date()));

		// 项目信息
		map.put("project", project);

		List<String> responseFile = new ArrayList<String>();
		Collections.addAll(responseFile, project.getResponseFile().replace("-@", "").split("@"));
		map.put("responseFile", responseFile);

		// 开标前30分钟
		map.put("bidStartTimeBefore", StringUtil.computeDate(project.getBidStartTime(), 0, 0, 0, 0, -30, 0));

		WordHandler world = new WordHandler();
		world.generateWord(path, map, worldXmlPath);// worldXmlPath
	}

	/**
	 * 竞价内容(响应文件)
	 * @param pi
	 * @param map
	 */
	private void getShotContentRes(ProjectInfo pi, Map map) {
//		String shotContentRes = "";
//		List<Resources> bidderResList = FileResUtil.findResources(pi.getId() + "," + pi.getWinningId());
//		List<String> responseFileList = Arrays.asList(pi.getResponseFile().split("@"));
//		int responseIndex = responseFileList.indexOf("竞价内容（必须与报价表内容（品名、品牌与型号、数量、单价、合计）一致，具体填写详见竞价内容简表");
//		if(responseIndex>-1){
//			responseIndex += 1;// 资源文件的businessId
//			for (Resources resource : bidderResList) {
//				if (resource.getFunctionFlog() == responseIndex) {// 竞价内容
//					shotContentRes += "<a href='../web/fileView?resId=" + resource.getId() + "'>" + "详情"// resource.getOldName()
//							+ "</a>  <br/>";
//					break;
//				}
//			}
//		}
//		map.put("shotContentRes", shotContentRes);
	}

	@Override
	public void publishContractPublicity(Execution execution) {
		String processId="257512";
		if(execution!=null){
			processId=execution.getProcessInstanceId();
		}
		
		Integer contactPass=(Integer) runtimeService.getVariable(execution.getId(), "contactPass");
		if(Integer.valueOf(ProjectStatus.SHOW_CONTACT.toString()).equals(contactPass)){
			ProjectInfo pi = projectInfoService.getProjectByProcessId(processId);
			
			pi.setCompetReleaseTime(new Date());//合同公示发布时间
			projectInfoService.saveOrUpdate(pi);
			
			// 发布合同公示
			WebContent web = generateContractPublicity(pi);
			projectInfoService.saveOrUpdate(web);
			LogUtil.addLog(new LogInfo("["+pi.getName()+"]"+"[发布合同公示] 执行了", "1", "系统", String.valueOf(LogUtil.LogType.ADD.ordinal()), this.getClass().getSimpleName(), "1"));
			System.err.println("NBExecutionServiceImpl.buyerChoiceBidderTaskService()------------------>[发布合同公示] 执行了");
		}
		
	}

	/**
	 * 生成合同公示
	 * @param pi
	 * @return
	 */
	@SuppressWarnings("all")
	private WebContent generateContractPublicity(ProjectInfo pi) {
		String tempContent=CommUtil.readStringFromFile(modelPath+"/"+"contractPublicity.html","utf-8");//模板文件目录
		Map map = new HashMap();
		map.put("project", pi);
		
		// 附件
		String resName = "";
		List<Resources> resList = FileResUtil.findResources(pi.getId());
		for (Resources resource : resList) {
			if (resource.getFunctionFlog() == 7) {// 上传的采购人合同
				resName += "<a href='../web/fileView?resId=" + resource.getId() + "'>" + pi.getName()+"-合同"//resource.getOldName()
						+ "</a><br/> ";
			}
		}
		map.put("resName", resName);
		
		//生成内容
		String content = CommUtil.freemarkerProcess(map,tempContent);

		// 插入新闻数据
		WebContent web = new WebContent();
		// 标题
		String title ="【"+pi.getCatagoryName()+"】"+  pi.getBuyName() + pi.getName() + "（" + pi.getCode() + "）合同公告";
		web.setTitle(title);
		web.setContent(content);
		web.setCreaterId(ActivitiMap.SUPERADMIN_ID);
		web.setCreateTime(new Date());
		web.setCreaterName("系统");
		web.setDeptId("1");
		web.setProjectId(pi.getId());
		web.setType("41");
		web.setIsDisplay(0);//显示
		web.setEndShowTime(pi.getContactEndTime());// 设置展示结束时间
		return web;
	}

	@Override
	public void publishReportPublicity(Execution execution) {
		String processId="257512";
		if(execution!=null){
			processId=execution.getProcessInstanceId();
		}
		
		Integer receiverPass=(Integer) runtimeService.getVariable(execution.getId(), "receiverPass");
		if(Integer.valueOf(ProjectStatus.RECEIVING_SHOWING.toString()).equals(receiverPass)){
			ProjectInfo pi = projectInfoService.getProjectByProcessId(processId);
			
			pi.setCompetReleaseTime(new Date());//验收报告公示发布时间
			projectInfoService.saveOrUpdate(pi);
			
			// 发布验收报告公示
			WebContent web = generateReportPublicity(pi);
			projectInfoService.saveOrUpdate(web);
			LogUtil.addLog(new LogInfo("["+pi.getName()+"]"+"[发布验收报告公示] 执行了", "1", "系统", String.valueOf(LogUtil.LogType.ADD.ordinal()), this.getClass().getSimpleName(), "1"));
			System.err.println("NBExecutionServiceImpl.buyerChoiceBidderTaskService()------------------>[发布验收报告公示] 执行了");
		}
		
	}

	/**
	 * 生成验收报告公示
	 * @param pi
	 * @return
	 */
	@SuppressWarnings("all")
	private WebContent generateReportPublicity(ProjectInfo pi) {
		String tempContent=CommUtil.readStringFromFile(modelPath+"/"+"reportPublicity.html","utf-8");//模板文件目录
		Map map = new HashMap();
		map.put("project", pi);
		
		// 附件
		String resName = "";
		List<Resources> resList = FileResUtil.findResources(pi.getId());
		for (Resources resource : resList) {
			if (resource.getFunctionFlog() == 20) {// 上传的验收报告
				resName += "<a href='../web/fileView?resId=" + resource.getId() + "'>" + pi.getName()+"-验收"//resource.getOldName()
						+ "</a><br/> ";
			}
		}
		map.put("resName", resName);
		
		//生成内容
		String content = CommUtil.freemarkerProcess(map,tempContent);

		// 插入新闻数据
		WebContent web = new WebContent();
		String title = pi.getBuyName() + pi.getName() + "（" + pi.getCode() + "）验收报告公示";
		web.setTitle("【"+pi.getCatagoryName()+"】"+ title);
		web.setContent(content);
		web.setCreaterId(ActivitiMap.SUPERADMIN_ID);
		web.setCreateTime(new Date());
		web.setCreaterName("系统");
		web.setDeptId("1");
		web.setProjectId(pi.getId());
		web.setType("42");
		web.setIsDisplay(0);//显示
		web.setEndShowTime(pi.getReceivingEndTime());// 设置展示结束时间
		return web;
	}

	@Override
	public void publishPreDocument(Execution execution) {
		//根据采购人选择的中标方式生成中标或者流标信息
        ProjectInfo proj=projectInfoService.getProjectByProcessId(execution.getProcessInstanceId());
        if(proj.getChooseType()!=null ){
            if(proj.getChooseType()==Constant.CHOOSE_TYPE_BUYERCHOICE){	//采购人选择中标单位
                this.publishHitPublicity(execution,false);
            }else if(proj.getChooseType()==Constant.CHOOSE_TYPE_BUYER_FLOW_DOWN){//采购人选择流标2
                this.publishFlowPublicity(execution,false);
            }else if(proj.getChooseType()==Constant.CHOOSE_TYPE_SYSTEMCHOICE){//采购人选择最低价3
                this.publishHitPublicity(execution,false);
            }else if(proj.getChooseType()== Constant.CHOOSE_TYPE_SYSTEM_LESS3_Flow){//有效标不足三家系统自动流标
                this.publishFlowPublicity(execution,false);
            }else{
                this.publishHitPublicity(execution,true);
            }
        }
	}
}